package com.web.ShoppingDemo.listener;

import java.util.Timer;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

import org.springframework.context.ApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import com.web.ShoppingDemo.util.BankUtil;
import com.web.ShoppingDemo.util.ProductTimerTask;
/**
 * 用于项目启动的初始化
 * @author THT
 *
 */
public class InitDataListener implements ServletContextListener {
	
	private ApplicationContext context = null;
	
	private ProductTimerTask productTimerTasker;
	
	private BankUtil bankUtil;
	
	@Override
	public void contextDestroyed(ServletContextEvent event) {
		
	}
	/**
	 * 项目启动的监听器,完成项目启动的数据的加载
	 */
	@Override
	public void contextInitialized(ServletContextEvent event) {
		/*ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext-*.xml");
		productService = (ProductService)context.getBean("productService");
		System.out.println(productService);*/
		//项目在启动的时候把Spring的配置文件通过监听器加载
		//存储在ServletContext中,可以进行获取
		//WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE
		/*ApplicationContext context = (ApplicationContext) event.getServletContext().getAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE);
		productService = (ProductService)context.getBean("productService");*/
		
		context = WebApplicationContextUtils.getWebApplicationContext(event.getServletContext());
		productTimerTasker =  (ProductTimerTask) context.getBean("productTimerTask");
		bankUtil = (BankUtil)context.getBean("bankUtil");
		
		//把application交给productTimerTask
		productTimerTasker.setApplication(event.getServletContext());
		//设置定时器,首页数据每隔一小时刷新(设置为守护进程)
		new Timer(true).schedule(productTimerTasker, 0, 1000*60*60);
		
		//项目加载银行的图标
		event.getServletContext().setAttribute("bankList", bankUtil.getBankImage(null));
		
	}

}
